//
//  SEGBasicTabBarController.m
//  SEGStandard
//
//  Created by 山刘 on 2019/4/16.
//  Copyright © 2019年 山刘. All rights reserved.
//

#import "SEGBasicTabBarController.h"
#import "SEGTabBar.h"
#import "SEGStaffDetailPresentationController.h"

#import "SEGBasicTabBarViewModel.h"
#import "SEGDoorPresentAnimation.h"
@interface SEGBasicTabBarController ()<ProtocolTabBarViewDelegate,UIViewControllerTransitioningDelegate>

/// tabBar
@property (nonatomic, strong) SEGTabBar *tabBar;
/// viewModel
@property (nonatomic, strong) SEGBasicTabBarViewModel *viewModel;

@end


@implementation SEGBasicTabBarController
@dynamic tabBar;

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tabBar = [[SEGTabBar alloc] init];
    self.tabBar.tabBarView.delegate = self;
    [self setValue:self.tabBar forKey:@"tabBar"];
    
    // 红点通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addRedDotOnTabbar:) name:SEGAddReddotNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenRedDotOnTabbar:) name:SEGHiddenRedDotNotification object:nil];
    
    // 请求广告展示配置 (每次登录&切换小区的时候)
    [self.viewModel seg_requestAdConfig];
    
    // 请求Tab菜单
    @weakify(self);
    [self.viewModel seg_requestMenuListCompletionHandler:^(SEGTabBarViewLayout *layout) {
        @strongify(self);
        [self.tabBar.tabBarView setWithLayout:layout];
        [self segAddNavis];
        self.tabBar.tabBarView.selectIndex = 0;
        self.selectedIndex = 0;
        
        // 等加载菜单数据之后再请求是否需要修改密码
        if (self.viewControllers.count > 0) {
            [self.viewModel seg_requestUserWhetherNeedUpdatePasswordCompletionHandler:^(NSString *codeType) {
                if ([codeType integerValue] == 3001) {
                    // 获取当前VC
                    UIViewController *currentVC = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
                    if (!currentVC) return;
                    
                    UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"安全提示" message:@"您的密码存在安全隐患，为了保障您的账号安全，请修改密码。" preferredStyle:UIAlertControllerStyleAlert];
                    [alter addAction:[UIAlertAction actionWithTitle:@"暂时不" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [self.viewModel seg_requestSubmitChangePasswordResult];
                    }]];
                    [alter addAction:[UIAlertAction actionWithTitle:@"去修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        UIViewController *changePasswordVC = [[SEGUhomeMediator sharedInstance] seg_initChangePasswordViewController:nil];
                        if (currentVC.navigationController) {
                            [currentVC.navigationController pushViewController:changePasswordVC animated:YES];
                        }
                    }]];
                    [currentVC presentViewController:alter animated:YES completion:nil];
                }
            }];
        }
    }];

    // 用来判断是否是调用启动广告，默认NO
    [self.viewModel seg_initLaunchAdvertismentCompletionHandler:^(SEGAdvlistType position) {
        // 启动广告
        if (![self.selectedViewController isKindOfClass:NSClassFromString([[SEGUhomeMediator sharedInstance] seg_getNaviControllerStringClass])]) return;
        UINavigationController *selectedNvi = (UINavigationController*)self.selectedViewController;
        UIViewController *topVC = selectedNvi.topViewController;
        if (!topVC) return;
        NSDictionary *params = @{@"position":@(position),@"vc":topVC};
        [[SEGUhomeMediator sharedInstance]seg_showLaunchAndPopWindowAdvertisement:params];
    }];
}
 
#pragma mark - 添加菜单
- (void)segAddNavis {
    [[SEGMenulist2Manager sharedManager].menuListTab enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *params = @{@"menuSid":ValueToString(obj.menuSid),
                                 @"action":ValueToString(obj.action),
                                 @"settingsId":ValueToString(obj.settingsId)};
        
        if ([obj.action isEqualToString:@"TAB_SHARE"]) {
            [self addChildViewController:[[SEGUhomeMediator sharedInstance] seg_initMainViewController:params] title:obj.serviceName imageName:@"" imageselectedName:@""];
        }
        if ([obj.action isEqualToString:@"TAB_SERVICE"]) {
            [self addChildViewController:[[SEGUhomeMediator sharedInstance] seg_initServiceViewController:params] title:obj.serviceName imageName:@"" imageselectedName:@""];
        }
        if ([obj.action isEqualToString:@"TAB_DOOR"]) {
            [self addChildViewController:[UIViewController new] title:obj.serviceName imageName:@"" imageselectedName:@""];
        }
        if ([obj.action isEqualToString:@"TAB_MESSAGE"]) {
            NSString *title = obj.serviceName;
            NSMutableDictionary *messageParams = [NSMutableDictionary dictionaryWithDictionary:params];
            [messageParams setValue:@(YES) forKey:@"isRootVC"];
            [self addChildViewController:[[SEGUhomeMediator sharedInstance] seg_initMessageRootViewController:messageParams] title:title imageName:@"" imageselectedName:@""];
        }
        if ([obj.action isEqualToString:@"TAB_ME"]) {
            [self addChildViewController:[[SEGUhomeMediator sharedInstance] seg_initMyRootViewController:params] title:obj.serviceName imageName:@"" imageselectedName:@""];
        }
        if ([obj.action isEqualToString:@"TAB_PROPERTY"]) { //物业服务
            [self addChildViewController:[[SEGUhomeMediator sharedInstance] seg_initOrderInputViewController:params] title:obj.serviceName imageName:@"" imageselectedName:@""];
        }
        if ([obj.action isEqualToString:@"TAB_WEB"]) { // 网页
            NSMutableDictionary *webParams = [NSMutableDictionary dictionaryWithDictionary:params];
            [webParams setValue:@(YES) forKey:@"isRootVC"];
            if (obj.linkURL) {
                [webParams setValue:obj.linkURL forKey:@"linkURL"];
            }
            [self addChildViewController:[[SEGUhomeMediator sharedInstance] seg_initTabWebViewLoadController:webParams] title:obj.serviceName imageName:@"" imageselectedName:@""];
        }
    }];
}

- (void)addChildViewController:(UIViewController*)childController title:(NSString*)title imageName:(NSString*)imageName imageselectedName:(NSString*)imageselectedName {
    // 添加子控制器
    childController.title = title;
    UINavigationController *nav = [[SEGUhomeMediator sharedInstance] seg_initNavigationController:@{@"vc":childController}];
    [self addChildViewController:nav];
}

/**
 * 跳转到指定的Tab
 * @author Sam
 */
- (void)segSelectedTab:(NSString*)action {
    // 处理点击对应Tab的红点
    for (SEGTabBarItemView *object in self.tabBar.tabBarView.backgroundScrollView.subviews) {
        if ([object isKindOfClass:[SEGTabBarItemView class]]) {
            if([object.layout.data.action isEqualToString:action]){
                self.tabBar.tabBarView.selectIndex = object.tag;
                return;
            }
        }
    }
    // 如果未匹配到对应tab 则直接跳转主页
    self.tabBar.tabBarView.selectIndex = 0;
//    self.selectedIndex = 0;
}

#pragma mark 点击开门按钮
- (void)clickComposeButton {
    @weakify(self);
    UIViewController *targetVC = [[SEGUhomeMediator sharedInstance] seg_showDoorWithType:0 showedCallBack:^(NSDictionary *info) {
        @strongify(self);
        // 开门成功之后的回调
        [self.viewModel seg_tabBarOpenDoorSuccessedWithInfo:info completionHandler:^(SEGAwardForwardType frowardType, NSDictionary * _Nonnull dicData) {
            [[SEGUhomeMediator sharedInstance] seg_dealWithCheckActivityResultDict:@{@"dicData":dicData,
                                                                                     @"frowardType":@(frowardType),
                                                                                     @"nav":self.selectedViewController,
                                                                                     @"fromType":@(SEGRedWalletFromType_OpenDoor),
                                                                                     @"vc":self}];
        }];
    } disappearCallBack:^{
//        UIViewController *currentVC = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
//        [[SEGUhomeMediator sharedInstance] seg_checkActivityLotteryBubble:@{@"vc" : currentVC}];
    }];
    
    if (targetVC) {
        UINavigationController *nav = [[SEGUhomeMediator sharedInstance] seg_initNavigationController:@{@"vc":targetVC}];
        nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark - 关于纷享刷新的一些方法
/**
 * 控制纷享刷新控件的展示和隐藏
 * @author Sam
 * @param imageShow  YES 展示，NO 隐藏
 */
- (void)segShowFreshImage:(BOOL)imageShow {
    for (SEGTabBarItemView *object in self.tabBar.tabBarView.backgroundScrollView.subviews) {
        if ([object isKindOfClass:[SEGTabBarItemView class]]) {
            if ([object.layout.data.action isEqualToString:@"TAB_SHARE"]) {
//                [object segFreshImageShow:imageShow];
            }
        }
    }
}

/**
 * 查看纷享刷新控件是否是需要刷新
 * @author Sam
 */
- (BOOL)segNeesFreshPGCData {
    __block BOOL isHidden = YES;//刷新图标隐藏，不用刷新
    for (SEGTabBarItemView *object in self.tabBar.tabBarView.backgroundScrollView.subviews) {
        if ([object isKindOfClass:[SEGTabBarItemView class]]) {
            if([object.layout.data.action isEqualToString:@"TAB_SHARE"]){
                isHidden = object.freshImageView.isHidden;
                break;
            }
        }
    }
    //NO:刷新图标展示，刷新
    return isHidden? NO : YES;
}

#pragma mark - ProtocolTabBarViewDelegate
- (void)segTabBarView:(SEGTabBarView *)view didSelectItemAtIndex:(NSInteger)index data:(SEGMenuListModel *)data {
    // 展示开门功能
    if ([data.action isEqualToString:@"TAB_DOOR"]) {
        [self clickComposeButton];
        return;
    }
    if ([self.selectedViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *selectNav = self.selectedViewController;
        selectNav.hidesBottomBarWhenPushed = NO;
        [selectNav popToRootViewControllerAnimated:NO];
    }
    
    self.selectedIndex = index;
    // 处理点击对应Tab的红点
    for (SEGTabBarItemView *object in self.tabBar.tabBarView.backgroundScrollView.subviews) {
        if ([object isKindOfClass:[SEGTabBarItemView class]]) {
            if([object.layout.data.action isEqualToString:data.action]){
                [[SEGUhomeMediator sharedInstance]seg_deleteRedDotWithId:@{@"idString":object.layout.data.settingsId}];
                object.redImageView.hidden = YES;
            }
        }
    }
    //其他的所有的不显示刷新
    for (SEGTabBarItemView *object in self.tabBar.tabBarView.backgroundScrollView.subviews) {
        if ([object isKindOfClass:[SEGTabBarItemView class]]) {
            if (![object.layout.data.action isEqualToString:data.action]) {
                [object segFreshImageShow:NO];
            }
        }
    }
    //判断纷享刷新控件是否展示
    if ([data.action isEqualToString:@"TAB_SHARE"]) {
        for (SEGTabBarItemView *object in self.tabBar.tabBarView.backgroundScrollView.subviews) {
            if ([object isKindOfClass:[SEGTabBarItemView class]]) {
                if ([object.layout.data.action isEqualToString:data.action]) {
                    if (!object.freshImageView.hidden) {
                        //如果为选中状态 刷新！
                        [[NSNotificationCenter defaultCenter] postNotificationName:SEGFreshItemNotification object:nil];
                    }
                    [object segFreshImageShow:YES];
                }
            }
        }
    }
}

#pragma mark - NSNotificationCenter（红点展示和隐藏的方法）
- (void)addRedDotOnTabbar:(NSNotification *)notification {
    if (notification.object) {
        NSArray *ids = notification.object;
        if (ids && [ids isKindOfClass:[NSArray class]]) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                for (SEGTabBarItemView *object in self.tabBar.tabBarView.backgroundScrollView.subviews) {
                    if ([object isKindOfClass:[SEGTabBarItemView class]]){
                        if ([ids containsObject:object.layout.data.settingsId]) {
                            if(object.isSelected){ //当前选中的tab
                                //把本地保存红点值删除
                                [[SEGUhomeMediator sharedInstance]seg_deleteRedDotWithId:@{@"idString":object.layout.data.settingsId}];
                                object.redImageView.hidden = YES;
                            }else{
                                object.redImageView.hidden = NO;
                            }
                        }
                    }
                }
            });
        }
    }
}
- (void)hiddenRedDotOnTabbar:(NSNotification *)notification {
    if (notification.object) {
        NSArray *ids = notification.object;
        if (ids && [ids isKindOfClass:[NSArray class]]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                for (SEGTabBarItemView *object in self.tabBar.tabBarView.backgroundScrollView.subviews) {
                    if ([object isKindOfClass:[SEGTabBarItemView class]]) {
                        if ([ids containsObject:object.layout.data.settingsId]) {
                            object.redImageView.hidden = YES;
                        }
                    }
                }
            });
        }
    }
}
#pragma mark - UIViewControllerTransitioningDelegate
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    
    SEGDoorPresentAnimation* animation = [[SEGDoorPresentAnimation alloc] init];
    animation.isPresent = YES;
    return animation;
}

#pragma mark - Getter
- (SEGBasicTabBarViewModel *)viewModel {
    if (!_viewModel) _viewModel = [[SEGBasicTabBarViewModel alloc] init];
    return _viewModel;
}

@end
